<?php

namespace Admin\Api\Controllers;

use Helpers\Main;
use Helpers\Tool;
use Helpers\HttpClient;
use Admin\Models\user\XhsysUser;
use Admin\Models\ask\XhaskSurvey;
use Admin\Models\stats\XhstatsWelfare;

class IndexController  extends ControllerBase
{

    public function indexAction()
    {
        $this->dispatcher->forward([
            'controller' => 'index',
            'action'     => 'notFound'
        ]);
        return false;
    }

    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)
            ->setJsonContent(['code' => 404, 'error' => '来到了未知领域...']);
    }

    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170830
     *
     * @SWG\Post(
     *     path="/api/index/login",
     *     tags={"Index"},
     *     consumes={"application/json"},
     *     summary="登陆",
     *     description="根据账号/手机号登陆，返回基本信息",
     *     @SWG\Parameter(name="body", in="body", description="验证信息", required=true,
     *         @SWG\Schema(
     *              required={"account", "password"},
     *              @SWG\Property(property="account", description="登陆名/手机号", type="string"),
     *              @SWG\Property(property="password", description="姓名", type="string"),
     *              @SWG\Property(property="loginType", description="登陆方式", type="string", enum={"phone", "logonName"}),
     *         )
     *     ),
     *     @SWG\Response(response="200", description="登陆成功",
     *         @SWG\Schema(
     *              @SWG\Property(property="userId", description="用户id", type="string"),
     *              @SWG\Property(property="userName", description="姓名", type="string"),
     *              @SWG\Property(property="logonName", description="登陆名", type="string"),
     *              @SWG\Property(property="phoneNum", description="电话", type="string"),
     *              @SWG\Property(property="userType", description="用户类型", type="string"),
     *              @SWG\Property(property="schoolId", description="学校id", type="string"),
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function loginAction()
    {
        if (!$this->request->isPost()){
            return $this->sendErrorResponse(400, '请求方式不正确！');
        }
        $request   = $this->request->getJsonRawBody(true);
        $account   = $request['account'];
        $password  = $request['password'];
        $loginType = Tool::getValue($request, 'loginType');
        if (!$account || !$password) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $params = [
            'columns' => [
                'iUserId AS userId',
                'sUserName AS userName',
                'sLogonName AS logonName',
                'sSelfPhone AS phoneNum',
                'iUserType AS userType',
                'iSchoolId AS schoolId',
                'sLogonPwd AS password'
            ],
            'conditions' => 'bDelete = 0 AND bDisable = 0'
        ];
        switch ($loginType) {
            case 'phone':       $params['conditions'] .= ' AND sSelfPhone = :account:'; break;
            case 'logonName':   $params['conditions'] .= ' AND sLogonName = :account:'; break;
            default:            $params['conditions'] .= ' AND (sLogonName = :account: OR sSelfPhone = :account:)';
        }
        $params['bind'] = ['account' => $account];
        $users = XhsysUser::find($params);
        if (!count($users)) {
            return $this->sendErrorResponse(400, '账号或手机号不存在');
        }
        foreach ($users as $user) {
            if (strtoupper($user->password) == strtoupper($password)) {
                unset($user->password);
                return $this->sendJsonResponse($user);
            }
        }
        return $this->sendErrorResponse(400, '密码错误');
    }

    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180426
     * modify by ck 20180522    添加用户存在判断
     *
     * @SWG\Get(
     *     path="/api/index/validCode",
     *     tags={"Index"},
     *     summary="获取验证码",
     *     description="根据手机号获取验证码",
     *     @SWG\Parameter(name="phone", in="query", description="手机号", required=true, type="string"),
     *     @SWG\Parameter(name="purpose", in="query", description="用途描述", type="string", enum={"register", "resetPassword", "resetPhone"}),
     *     @SWG\Parameter(name="channelId", in="query", description="发送渠道id", type="string"),
     *     @SWG\Response(response="200", ref="#/responses/Success"),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function validCodeAction()
    {
        if (!$this->request->isGet()){
            return $this->sendErrorResponse(400, '请求方式不正确');
        }
        $phone      = $this->request->getQuery('phone', 'string');
        $purpose    = $this->request->getQuery('purpose', 'string', '');
        $channelId  = $this->request->getQuery('channelId', 'string', '');
        if (!$phone) {
            return $this->sendErrorResponse(400, '手机号不能为空');
        }
        try {
            $userCount = XhsysUser::count([
                'conditions' => 'bDelete = 0 AND (sSelfPhone = :phone: OR sLogonName = :phone:)',
                'bind'       => ['phone' => $phone]
            ]);
            switch ($purpose) {
                case 'register':
                    if ($userCount) {
                        throw new \Exception('手机号已存在');
                    }
                    break;
                case 'resetPassword':
                case 'resetPhone':
                    if (!$userCount) {
                        throw new \Exception('用户不存在');
                    }
                    break;
                default: break;
            }
            $result = Main::sendValidCode($phone, null, 'api', $purpose, $channelId);
            if (!$result) {
                throw new \Exception('发送验证码失败');
            }
            return $this->sendSuccessResponse('验证码发送成功');
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171212
     *
     * @SWG\Get(
     *     path="/api/index/checkSurvey",
     *     tags={"Index"},
     *     summary="检查是否有问卷",
     *     description="检查是否有问卷",
     *     @SWG\Parameter(name="userId", in="query", description="用户id", required=true, type="integer"),
     *     @SWG\Parameter(name="schoolId", in="query", description="学校id", type="integer"),
     *     @SWG\Parameter(name="userType", in="query", description="用户类型", type="integer"),
     *     @SWG\Parameter(name="accessToken", in="query", description="验证信息", type="string"),
     *     @SWG\Response(response="200", description="获取问卷成功",
     *      @SWG\Schema(
     *          @SWG\Property(property="total", description="问卷总数", type="integer"),
     *          @SWG\Property(property="title", description="标题", type="array"),
     *          @SWG\Property(property="remind", description="提示语", type="array"),
     *          @SWG\Property(property="url", description="问卷地址", type="string"),
     *          @SWG\Property(property="target", description="打开方式", type="string", enum={"webview", "msg"}),
     *      ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function checkSurveyAction()
    {
//        return $this->sendJsonResponse([
//            'total' => 0,
//            'title' => [],
//            'remind' => [],
//            'url' => '',
//            'target' => 'webview'
//        ]);
        if (!$this->request->isGet()) {
            return $this->sendErrorResponse(400, '请求方式不正确');
        }
        $userId   = $this->request->getQuery('userId', 'int');
        $schoolId = $this->request->getQuery('schoolId', 'int');
        $userType = $this->request->getQuery('userType', 'int');
        $token    = $this->request->getQuery('accessToken', 'string');
        try {
            $surveyList = XhaskSurvey::getAllowAttendList($userId, $schoolId, $userType);
//            $surveyList = [];
            $url = Tool::getValue(Main::getConfigByName('admin'), 'url', 'https://admin.yunzuoye.net');
            $result = [
                'total' => count($surveyList),
                'title' => $surveyList ? array_column($surveyList, 'title') : [],
                'remind'=> $surveyList ? array_column($surveyList, 'remind') : [],
                'url'   => Tool::buildPath($url, 'survey/?userId=' . $userId),
                'target'=> 'webview',
//                'survey'=> $surveyList
            ];
            //处理是否有其他问卷
            if ($result['total'] == 0) {
                $this->checkOtherSurvey($result, $userId, $schoolId, $userType);
            }
            return $this->sendJsonResponse($result);
        } catch (\Exception $e) {
            $error = explode('|', $e->getMessage());
            return $this->sendErrorResponse(400, $error[0], $error[1] ?: '');
        }
    }

    /**
     * 检查是否有其他问卷需要填写
     *
     * @param $result
     * @param $userId
     * @param $schoolId
     * @param $userType
     * @return bool
     *
     * create by ck 20180402
     */
    private function checkOtherSurvey(&$result, $userId, $schoolId, $userType)
    {
        //获取公益课堂
//        if ($userType == 1 && $this->checkWelfareKokugaku($userId, $schoolId)) {
//            $result['total'] = 1;
//            $result['url']   = Tool::buildUrl('survey/welfare/kokugaku', ['userId' => $userId]);
//            return true;
//        }

        //获取课程问卷
        if ($userType == 1) {
            $httpClient = new HttpClient(Main::getConfigByName('CA102002')['url']);
            $response   = $httpClient->postJson(
                '/course/common/reserve/main',
                ['source' => 'platform', 'userId' => $userId]
            );
            if ($response->isSuccess()) {
                $data = $response->toArray();
                if (isset($data['url']) && $data['url']) {
                    $result['total'] = 1;
                    $result['url']   = $data['url'];
                    $result['title'] = [$data['name']];
                    return true;
                }
            }
        }

        //获取暑假安全通知
//        $schoolIds = [4164,4180,4649,4179,4842,4856,4895,4181,760,4199,4852,781,4861,3179,3577,406,3190,4175,4176,4667,
//            4849,4671,4095,4094,4655,4653,4652,4851,4878,1471,4178,4844,3638,4215,4648,4900,845,3496,3495,3613,4074,4073,
//            4075,4106,4070,4111,4672,4854,4860,4897,4905,3189,4068,4210,4171,4858,899,4099,4656,4110,4161,4630,3605,4057,
//            4102,4101,4650,4654,4104,4103,4212,3261,4173,4172,4658,3637,4659,4847,4867,4663,4855,2747];
//        if ($userType == 1 && in_array($schoolId, $schoolIds)) {
//        if ($userType == 1) {
//            $startTime = strtotime('2018-05-25 00:00:00');
//            $endTime   = strtotime('2018-09-01 00:00:00');
//            $nowTime   = time();
//            if ($nowTime < $startTime || $nowTime > $endTime) {
//                return false;
//            }
//            $needTime = strtotime(date('Y-m-d H:i:s', $nowTime) . '-7 day');
//
//            $hasWarning = XhstatsWelfare::count([
//                'conditions' => 'iUserId = :userId: AND iType = 2 AND tCreateDate > :needTime:',
//                'bind'       => ['userId' => $userId, 'needTime' => $needTime]
//            ]);
//            if (!$hasWarning) {
//                $result['total']  = 1;
//                $result['url']    = Tool::buildUrl(
//                    'survey/summerSafe/index.html',
//                    ['userId' => $userId, 'schoolId' => $schoolId]
//                );
//                $result['title']  = ['暑假通知'];
//                $result['remind'] = ['你有一份假期通知，请及时查看！'];
//                return true;
//            }
//        }

        return true;
    }

    /**
     * 检查国学报名情况-临时
     *
     * @param $userId
     * @return bool
     *
     * create by ck 20180208
     */
//    private function checkWelfareKokugaku($userId, $schoolId)
//    {
//        $startTime = strtotime('2018-02-09 00:00:00');
//        $endTime   = strtotime('2018-02-12 00:00:00');
//        $nowTime   = time();
//        if ($schoolId == 3563 && $nowTime < $endTime) {
//            return true;
//        }
//        if ($nowTime < $startTime || $nowTime > $endTime) {
//            return false;
//        }
//        if (XhstatsWelfare::checkExist($userId, 1)) {
//            return false;
//        }
//        return true;
//    }

}

